package me.zhengjie.modules.device.service.impl;

import me.zhengjie.modules.device.domain.AccessDevice;
import me.zhengjie.utils.ValidationUtil;
import me.zhengjie.modules.device.repository.AccessDeviceRepository;
import me.zhengjie.modules.device.service.AccessDeviceService;
import me.zhengjie.modules.device.service.dto.AccessDeviceDTO;
import me.zhengjie.modules.device.service.mapper.AccessDeviceMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import java.util.Optional;

/**
* @author 张鹏
* @date 2019-05-07
*/
@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class AccessDeviceServiceImpl implements AccessDeviceService {

    @Autowired
    private AccessDeviceRepository accessDeviceRepository;

    @Autowired
    private AccessDeviceMapper accessDeviceMapper;

    @Override
    public AccessDeviceDTO findById(Long id) {
        Optional<AccessDevice> accessDevice = accessDeviceRepository.findById(id);
        ValidationUtil.isNull(accessDevice,"AccessDevice","id",id);
        return accessDeviceMapper.toDto(accessDevice.get());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public AccessDeviceDTO create(AccessDevice resources) {
        return accessDeviceMapper.toDto(accessDeviceRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(AccessDevice resources) {
        Optional<AccessDevice> optionalAccessDevice = accessDeviceRepository.findById(resources.getId());
        ValidationUtil.isNull( optionalAccessDevice,"AccessDevice","id",resources.getId());

        AccessDevice accessDevice = optionalAccessDevice.get();
        // 此处需自己修改
        resources.setId(accessDevice.getId());
        accessDeviceRepository.save(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(Long id) {
        accessDeviceRepository.deleteById(id);
    }
}